import axios from '../utils/request.js'
import {
	getSession,
	setSession
} from '../utils/dataStorage.js'
import qs from 'qs'//引入qs


export function save(fun) {
	return axios.post('/sys/department/save', fun);
}

export function deleteById(id) {
	return axios.delete('/sys/department/' + id);
}

export function findById(id) {
	return axios.get('/sys/department/' + id);
}

export function departmentTree(params) {
	return axios.get('/sys/department/tree?' + qs.stringify(params));
}

export async function departmentList(params) {
	return await axios.get('/sys/department/list?' + qs.stringify(params),{'closeLoading':true});
}

export function departmentMap(departmentName) {
	return new Promise((resolve, reject) => {
		let departmentDic = getSession('DEPARTMENT_LIST');
		if (departmentDic) {//如果缓存有,且未过期,则返回缓存值
			try {
				departmentDic = JSON.parse(departmentDic);
				if (departmentDic && departmentDic["expired"] && parseInt(departmentDic["expired"]) > parseInt(new Date().getTime() / 1000)) {
					return resolve(departmentDic.content);					
				}
			} catch (e) {}
		}
		//如果缓存没有值  或  缓存值过期,则向后台请求, 将请求结果重新缓存,并返回
		departmentList(departmentName).then(data => {
			if (data) {
				let expired = parseInt(new Date().getTime() / 1000) + 300; //设置过期时间 5 * 60 (5分钟)
				departmentDic = {
					"expired": expired,
					"content": data
				};
				setSession('DEPARTMENT_LIST', JSON.stringify(departmentDic));
				return resolve(departmentDic.content);				
			}
		}).catch(exception => {
			reject({});
		});
	});
}
